const ChatHandler = require('./chatHandler');
const WebSocketUtils = require('./utils');

function setupAdvancedWebSocketServer(server) { //设置高级WebSocket服务器初始化函数

    const wsServers = new Map(); //创建WebSocket服务器存放实例的Map

    // 初始化各个服务处理器
    const chatHandler = new ChatHandler();
    // 注册服务器
    wsServers.set('/ws/chat', chatHandler.getServer());


    // 处理HTTP升级请求
    server.on('upgrade', (request, socket, head) => {
        const pathname = new URL(request.url, `http://${request.headers.host}`).pathname;
        console.log('WebSocket升级请求路径:', pathname);

        const wss = wsServers.get(pathname);//获取WebSocket服务器实例
        if (wss) { //如果存在
            wss.handleUpgrade(request, socket, head, (ws) => {
                console.log("协议升级成功");
                //设置连接日志
                WebSocketUtils.setupConnectionLogging(ws, wss);
                //触发连接事件
                wss.emit('connection', ws, request); //触发连接事件，触发后执行回调函数，回调函数是ws.handleUpgrade的回调函数
            });
        } else {
            console.log("路径不匹配，关闭连接");
            socket.destroy();
        }
    });

    // 返回所有WebSocket服务器实例和工具函数
    return {
        wsServers,
        chatWss: chatHandler.getServer(),
    };
}

module.exports = setupAdvancedWebSocketServer;